package com.app.mail.controller;

import com.alibaba.fastjson.JSONObject;
import com.app.mail.dto.StoreMailDto;
import com.app.mail.model.StoreMail;
import com.app.mail.service.MailService;
import com.app.sysmodule.exception.ServiceException;
import com.app.sysmodule.excuteUtil.ThreadPoolExecutor;
import com.app.sysmodule.reponse.JsonResult;
import com.app.sysmodule.utils.ConcurrentHashMapUtil;
import com.app.sysmodule.utils.JsonData;
import com.app.sysmodule.utils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by song on 2018/1/31.
 */
@Controller
@RequestMapping("/mail")
public class MailController {
    private static Logger logger = Logger.getLogger(MailController.class);
    @Autowired
    private MailService mailService;

    /**
     * 获取邮箱管理员列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getMailManageList", method = RequestMethod.GET)
    public ModelAndView getMailManageList() {
        ModelAndView view = new ModelAndView("/mail/mailList");
        try {
            List<StoreMailDto> list = mailService.getMailManageList();
            view.addObject("list", list);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("getMailManageList:"+e.getMessage());
        }
        return view;
    }

    /**
     * 异步删除
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteMaiManage",method = RequestMethod.POST)
    public String deleteMaiManage(HttpServletRequest request , HttpServletResponse response){
        try{
           String id = request.getParameter("id");
            if(StringUtils.isNotEmpty(id)){
                mailService.deleteMailManage(Long.parseLong(id));
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("deleteMaiManage:"+e.getMessage());
            return null;
        }
        return "success";
    }
    /**
     * 进入编辑页面
     */
    @ResponseBody
    @RequestMapping(value = "/editMaiManage", method = RequestMethod.GET)
    public ModelAndView editMaiManage(HttpServletRequest request,HttpServletResponse response) {
        ModelAndView view = new ModelAndView("/mail/mailEdit");
        StoreMailDto storeMailDto = new  StoreMailDto();
        try {
            String id = request.getParameter("id");
            if(null != id){
                storeMailDto = mailService.editMaiManage(Long.parseLong(id));
            }

            view.addObject("dto", storeMailDto);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("editMaiManage:"+e.getMessage());
        }
        return view;
    }
    /**
     * 保存编辑
     */
    @ResponseBody
    @RequestMapping(value = "/sageMaiManage", method = RequestMethod.POST)
    public ModelAndView sageMaiManage(HttpServletRequest request,HttpServletResponse response) {
        ModelAndView view = new ModelAndView("redirect:/mail/getMailManageList");
        ModelAndView viewerr = new ModelAndView("/mail/mailEdit");
        StoreMailDto storeMailDto = new  StoreMailDto();
        try {
            String id = request.getParameter("id");
            String emailAccount = request.getParameter("emailAccount");
            String userName = request.getParameter("userName");
            String stationName = request.getParameter("stationName");
            String remark = request.getParameter("remark");
            String isSend = request.getParameter("isSend");
            if(StringUtils.isEmpty(emailAccount)){
                viewerr.addObject("err","邮箱账号不能为空");
                return viewerr;
            }
            if(StringUtils.isEmpty(userName)){
                viewerr.addObject("err","人员名称不能为空");
                return viewerr;
            }
            StoreMail storeMail = new StoreMail();
            if(StringUtils.isNotEmpty(id)){
                storeMail.setId(Long.parseLong(id));
            }
            storeMail.setUserName(userName);
            storeMail.setEmailAccount(emailAccount);
            if(StringUtils.isNotEmpty(isSend)){
                storeMail.setIsSend(Long.parseLong(isSend));
            }else {
                storeMail.setIsSend(0l);
            }
            storeMail.setRemark(remark);
            storeMail.setStationName(stationName);
            mailService.saveMailManage(storeMail);
            view.addObject("dto", storeMailDto);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("editMaiManage:"+e.getMessage());
        }
        return view;
    }
    /**
     * 进入新增页面
     */
    @ResponseBody
    @RequestMapping(value = "/createMaiManage", method = RequestMethod.GET)
    public ModelAndView createMaiManage(HttpServletRequest request,HttpServletResponse response) {
        ModelAndView view = new ModelAndView("/mail/mailEdit");
        return view;
    }
    /**
     * 修改发送状态
     */
    @ResponseBody
    @RequestMapping(value = "/updateIsSend",method = RequestMethod.POST)
    public String updateIsSend(HttpServletRequest request,HttpServletResponse response){
        String id = request.getParameter("id");
        String isSend = request.getParameter("isSend");
        if(StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(isSend)){
            try {
                mailService.updateIsSend(id,isSend);
            }catch (Exception e){
                e.printStackTrace();
                logger.error(e.getMessage());
                return null;
            }
        }
        return "success";
    }

    /**
     * 修改发送状态
     */
    @ResponseBody
    @RequestMapping(value = "/sendMail",method = RequestMethod.POST)
    public String sendMail(HttpServletRequest request,HttpServletResponse response){
        try {
            final String bucketName = PropertyUtils.getProperty("aliyun_bucketName");
            String type = "02";
            String version="2.5.1";
            final String serverVersion="V3.18.3.1";
            String fileSize ="15.00MB";
            final String remark="测试";
            //异步发送邮件
            final String downUrl = PropertyUtils.getProperty("download_url") + "homePage.jsp?version=" + serverVersion + "&source=scm";
            final String pathQrcode = request.getServletContext().getRealPath("/");
            final String finalVersion = version;
            final String finalFileSize = fileSize;
            final String finalType = type;
            final String osName ="测试环境";
            ThreadPoolExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date=new Date();
                        String time = sdf.format(date);
                        mailService.sendMail(finalVersion, serverVersion, finalFileSize, time, remark, downUrl, finalType, pathQrcode,bucketName);
                    } catch (ServiceException e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return "success";
    }
    @ResponseBody
    @RequestMapping(value = "/testMail",method = RequestMethod.POST)
    public String testMail(HttpServletRequest request,HttpServletResponse response) {
        try{
            final String username = PropertyUtils.getProperty("mailUserName");
            final String password = PropertyUtils.getProperty("mailPassword");
            String appType = "Android";
            Integer port = Integer.parseInt(PropertyUtils.getProperty("mailPort"));
            JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
            javaMailSender.setHost("smtp.exmail.qq.com");//链接服务器
            javaMailSender.setPort(port);
            javaMailSender.setUsername(username);//账号
            javaMailSender.setPassword(password);//密码
            javaMailSender.setDefaultEncoding("UTF-8");
            final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            Properties properties = new Properties();
            properties.setProperty("mail.smtp.auth", "true");//开启认证
            properties.setProperty("mail.debug", "true");//启用调试
            properties.setProperty("mail.smtp.timeout", "1000");//设置链接超时
            properties.setProperty("mail.smtp.port", "465");//设置端口
            properties.setProperty("mail.smtp.socketFactory.port", "465");//设置ssl端口
            properties.setProperty("mail.smtp.socketFactory.fallback", "false");
            properties.setProperty("mail.smtp.host", "smtp.exmail.qq.com");
            properties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 重写验证方法，填写用户名，密码
                    return new PasswordAuthentication(username, password);
                }
            };
            javaMailSender.setJavaMailProperties(properties);
            // 设置utf-8或GBK编码，否则邮件会有乱码
            try {
                MimeMessage msg = javaMailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(msg, true);
                helper.setFrom(username);

                helper.setTo("sgp@acewill.cn");
                helper.setSubject("====app版本升级提醒====");
                helper.setText("ceshi", true);
                //发送邮件
                javaMailSender.send(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return "success";
    }

    }

